import { provide, inject, ref, unref } from 'vue'
import { message as Message } from 'ant-design-vue'
import { debounce } from 'lodash-es'
import { nanoid } from 'nanoid'
import { tagList } from '@/api/tag.js'
/**
 * Symbol
 */
export const columnsSymbol = Symbol('columns')
export const dataSourceSymbol = Symbol('dataSource')
export const querySymbol = Symbol('query')
export const lineheightSymbol = Symbol('lineheight')
export const loadingSymbol = Symbol('loading')
export const rowSelectionSymbol = Symbol('rowSelection')
export const rowSelectionActiveSymbol = Symbol('rowSelectionActive')
export const expandedKeysSymbol = Symbol('expandedKeys')
export const parentIdSymbol = Symbol('parentId')
export const nameRefsSymbol = Symbol('nameRefs')

/**
 * 注册
 */
export function useProvideContextRegistry() {
  let columns = ref([])
  let dataSource = ref([])
  let query = ref({})
  let lineheight = ref()
  let loading = ref(false)
  let selectedRowKeys = ref([])
  let expandedKeys = ref([])
  let parentId = ref()
  let nameRefs = ref({})
  let rowSelection = {
    selectedRowKeys,
    onChange: keys => {
      selectedRowKeys.value = keys
    },
    getCheckboxProps: record => ({
      disabled: record.type === 1 || record.isPublished === 1,
    }),
  }
  let rowSelectionActive = ref(false)
  provide(columnsSymbol, columns)
  provide(dataSourceSymbol, dataSource)
  provide(querySymbol, query)
  provide(lineheightSymbol, lineheight)
  provide(loadingSymbol, loading)
  provide(rowSelectionSymbol, rowSelection)
  provide(rowSelectionActiveSymbol, rowSelectionActive)
  provide(expandedKeysSymbol, expandedKeys)
  provide(parentIdSymbol, parentId)
  provide(nameRefsSymbol, nameRefs)
}

/**
 * 获取值
 */
export function useColumns() {
  return inject(columnsSymbol)
}
export function useDataSource() {
  return inject(dataSourceSymbol)
}
export function useQuery() {
  return inject(querySymbol)
}
export function useLineheight() {
  return inject(lineheightSymbol)
}
export function useLoading() {
  return inject(loadingSymbol)
}
export function useRowSelection() {
  return inject(rowSelectionSymbol)
}
export function useRowSelectionActive() {
  return inject(rowSelectionActiveSymbol)
}
export function useExpandedKeys() {
  return inject(expandedKeysSymbol)
}
export function useParentId() {
  return inject(parentIdSymbol)
}
export function useNameRefs() {
  return inject(nameRefsSymbol)
}
/**
 * 管理工具
 */
export function useDataSourceManager() {
  let dataSource = useDataSource()
  let query = useQuery()
  let loading = useLoading()
  let expandedKeys = useExpandedKeys()
  let parentId = useParentId()
  let update = debounce(async () => {
    loading.value = true
    let { current, pageSize, ...otherQuery } = query.value
    try {
      let result = await tagList({ pageIndex: current, pageSize })
      query.value.total = result?.data?.totalCount || 0
      dataSource.value = result?.data
      dataSource.value.forEach(node => cleanEmptyChildren(node))
      // dataSource.value = ds
      loading.value = false
    } catch (e) {
      Message.error('列表加载失败')
      loading.value = false
    }
  }, 300)
  function createEmpty() {
    let tagId = nanoid()
    dataSource.value = [
      {
        tagId: tagId,
        tagName: '',
        type: 0,
        editing: true,
        loading: false,
        new: true,
      },
      ...dataSource.value,
    ]
  }
  function removeEmpty() {
    dataSource.value = dataSource.value.filter(({ new: n }) => !n)
  }
  function createTagEmpty(targetId) {
    parentId.value = targetId
    let tagId = nanoid()
    // 遍历数据数组
    dataSource.value.forEach(e => {
      if (e.tagId === targetId) {
        if (!e.children) {
          e.children = []
        }
        e.children.unshift({
          tagId: tagId,
          tagName: '',
          type: 1,
          editing: true,
          loading: false,
          new: true,
          parentId: targetId,
        })
      }
    })
    expandedKeys.value = [...expandedKeys.value, targetId]
  }
  function removeTagEmpty(targetId) {
    dataSource.value.forEach(e => {
      if (e.tagId === targetId) {
        e.children = e.children.filter(({ new: n }) => !n)
      }
    })
  }
  return { update, createEmpty, removeEmpty, createTagEmpty, removeTagEmpty }
}
export function useQueryManager() {
  let query = useQuery()
  return {
    set(newQuery) {
      query.value = unref(newQuery)
    },
    assign(newQuery) {
      query.value = Object.assign({}, query.value, newQuery)
    },
  }
}
// 递归地清理单个树结构中的空children
function cleanEmptyChildren(node) {
  if (Array.isArray(node.children) && node.children.length === 0) {
    delete node.children
  } else if (node.children && node.children.length > 0) {
    for (let i = 0; i < node.children.length; i++) {
      cleanEmptyChildren(node.children[i])
    }

    // 再次检查是否为空数组，因为子节点可能已经被删除
    if (node.children.length === 0) {
      delete node.children
    }
  }
}
/**
 * 数据
 */
let ds = [
  {
    tagName: '标签组1',
    type: 0,
    tagId: '1',
    orderBy: 1,
    isPublished: 0,
    children: [
      {
        tagName: '标签1-1',
        type: 1,
        tagId: '11',
        orderBy: 2,
        isPublished: 0,
      },
      {
        tagName: '标签1-2',
        type: 1,
        tagId: '12',
        orderBy: 3,
        isPublished: 0,
      },
      {
        tagName: '标签1-3',
        type: 1,
        tagId: '13',
        orderBy: 4,
        isPublished: 0,
      },
    ],
  },
  {
    tagName: '标签组2',
    type: 0,
    tagId: '2',
    orderBy: 5,
    isPublished: 1,
    children: [
      {
        tagName: '标签2-1',
        type: 1,
        tagId: '21',
        orderBy: 6,
        isPublished: 1,
      },
      {
        tagName: '标签2-2',
        type: 1,
        tagId: '22',
        orderBy: 7,
        isPublished: 1,
      },
      {
        tagName: '标签2-3',
        type: 1,
        tagId: '23',
        orderBy: 8,
        isPublished: 1,
      },
    ],
  },
]
